package com.github.tomakehurst.wiremock.admin.tasks;

import com.github.tomakehurst.wiremock.admin.AdminTask;
import com.github.tomakehurst.wiremock.admin.model.ListStubMappingsResult;
import com.github.tomakehurst.wiremock.admin.model.StubConditionQuery;
import com.github.tomakehurst.wiremock.common.Errors;
import com.github.tomakehurst.wiremock.common.Json;
import com.github.tomakehurst.wiremock.common.url.PathParams;
import com.github.tomakehurst.wiremock.core.Admin;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder.responseDefinition;
import static java.net.HttpURLConnection.HTTP_OK;

/**
 * 多条件查询 Stub 的 Admin Task
 */
public class FindStubMappingsByConditionsTask implements AdminTask {
    // 日志对象（WireMock 统一 SLF4J 日志）
    private static final Logger LOG = LoggerFactory.getLogger(FindStubMappingsByConditionsTask.class);

    // 统一错误码（便于维护）
    private static final int ERROR_EMPTY_BODY = 10;    // 请求体为空
    private static final int ERROR_INVALID_JSON = 11; // JSON 格式错误
    private static final int ERROR_BUSINESS = 12;     // 业务逻辑异常

    @Override
    public ResponseDefinition execute(Admin admin, ServeEvent serveEvent, PathParams pathParams) {
        try {
            // 1. 获取请求对象与请求体，判断是否为空
            Request request = serveEvent.getRequest();
            String requestBody = request.getBodyAsString();
            if (requestBody == null || requestBody.trim().isEmpty()) {
                LOG.warn("Stub condition query failed: request body is empty. Request URL: {}", request.getAbsoluteUrl());
                return ResponseDefinition.badRequest(
                        Errors.single(ERROR_EMPTY_BODY, "请求体不能为空(required: name/demandId/createUserId/updatedAt)")
                );
            }

            // 2. 解析请求体（显式捕获 JSON 反序列化异常）
            StubConditionQuery query;
            query = Json.read(requestBody, StubConditionQuery.class);

            // 3. 参数校验（自动修正页大小、空条件等）
            query.validate();
            LOG.debug("条件查询参数: {}", Json.write(query)); // 调试日志，打印校验后的参数

            // 4. 调用 Admin 接口执行业务查询（依赖 WireMockApp 实现）
            ListStubMappingsResult result = admin.findStubMappingsByConditions(query);

            // 5. 构建正常响应（JSON 格式，含分页信息）
            LOG.debug("Stub condition query success: total={} stubs", result.getMappings().size());
            return responseDefinition()
                    .withStatus(HTTP_OK)
                    .withHeader("Content-Type", "application/json;charset=UTF-8")
                    .withBody(Json.write(result))
                    .build();

        } catch (Exception e) {
            // 捕获所有未显式处理的异常（如存储层错误、查询超时等）
            LOG.error("Stub condition query failed: unexpected business error", e);
            return responseDefinition()
                    .withStatus(500)
                    .withHeader("Content-Type", "application/json;charset=UTF-8")
                    .withBody(Json.write(
                            Errors.single(ERROR_BUSINESS, "Failed to find stubs: " + e.getMessage())
                    ))
                    .build();
        }
    }
}